﻿using Dapper;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using OMG.Fill.Vegetable.Model;
using OMG.Fill.Vegetable.Model.Ent;
using ProjectShare;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;

namespace OMG.Fill.Vegetable.Service
{
    /// <summary>
    /// 表1蔬菜基本情况调查T_VegBasicInfo通用操作类
    /// </summary>
    public class VegBasicInfoServices : VegBasicInfos
    {
        DictServices dict = new DictServices();
        public Pager<List<VegBasicInfoEntity>> GetPageList(VegBasicInfoQuery query)
        {
            Pager<List<VegBasicInfoEntity>> obj = new Pager<List<VegBasicInfoEntity>>();
            var paramlist = new DynamicParameters();
            string strWhereSql = "";//from 表在下面，需完善其他查询条件在这里接的写，格式为："and xxx=@xxx空格,如下注释部分代码所示："
            //if (!string.IsNullOrEmpty(query.GroupCode))
            //{
            //  strWhereSql += "and GroupCode = @GroupCode ";
            //  paramlist.Add("GroupCode", query.GroupCode);
            //}
            string strFromSql = "from dbo.T_VegBasicInfo where 1=1 " + strWhereSql;
            string strTotal = "select count(1)" + strFromSql + strWhereSql;
            string strOrderSql = "";//自定义完成order by语句
            string strSql = @"select * from (select *,ROW_NUMBER() over (order by Id ) as RowNumber " + strFromSql + ") as t ";
            strSql += "where t.RowNumber between  @minRow and @maxRow" + strOrderSql;
            paramlist.Add("minRow", query.MinRow);
            paramlist.Add("maxRow", query.MaxRow);
            try
            {
                using (var dbCon = ConnectFactory.GetOpenConnection())
                {
                    obj.rows = dbCon.Query<VegBasicInfoEntity>(strSql, paramlist).ToList();
                    obj.total = dbCon.Query<int>(strTotal, paramlist).FirstOrDefault();
                    obj.status = DefaultKey.SuccessResult;
                    obj.message = "获取成功！";
                    dbCon.Dispose();//数据库连接释放
                    return obj;
                }
            }
            catch (Exception ex)
            {
                obj.status = DefaultKey.ErrorResult;
                obj.message = ex.ToString().Trim();
                LogHelper.ErrorLog("获取表1蔬菜基本情况调查T_VegBasicInfo分页列表失败", ex);
                return obj;
            }
        }
        /// <summary>
        /// 蔬菜外销情况表----数据填报(数据更新)
        /// </summary>
        /// <returns></returns>
        public ResResult<VegBasicInfoEntity> UpdateModelList(VegBasicInfoEntity model)
        {
            ResResult<VegBasicInfoEntity> result = new ResResult<VegBasicInfoEntity>();
            string strSql = @"UPDATE dbo.T_VegBasicInfo set ";
            strSql += "ReportId = @ReportId,";
            strSql += "AreaCode = @AreaCode,";
            strSql += "VegArea = @VegArea,";
            strSql += "PerennialArea = @PerennialArea,";
            strSql += "SeasonArea = @SeasonArea,";
            strSql += "WSArea = @WSArea,";
            strSql += "SFArea = @SFArea,";
            strSql += "LiquidArea = @LiquidArea,";
            strSql += "FacilityArea = @FacilityArea,";
            strSql += "Remark = @Remark,";
            strSql += "AddUser = @AddUser,";
            strSql += "AddTime = @AddTime,";
            strSql += "UpdateUser = @UpdateUser,";
            strSql += "UpdateTime = @UpdateTime";
            strSql += " where Id = @Id";
            if (model != null)
            {
                using (var dbCon = ConnectFactory.GetOpenConnection())
                {
                    using (var trans = dbCon.BeginTransaction())
                    {
                        try
                        {
                            dbCon.Execute(strSql, model, trans);
                            result.message = "更新蔬菜基本情况数据成功。";
                            result.status = DefaultKey.SuccessResult;
                            trans.Commit();
                        }
                        catch (Exception ex)
                        {
                            result.message = "更新蔬菜基本情况异常,异常信息:" + ex.ToString().Trim();
                            result.status = DefaultKey.ErrorResult;
                            LogHelper.WriteLog("更新蔬菜基本情况异常,异常信息:" + ex.ToString().Trim());
                            trans.Rollback();
                        }
                    }
                }
            }
            return result;
        }
        /// <summary>
        /// 判定是否生成过报表
        /// </summary>
        /// <param name="reportId"></param>
        /// <returns>没生成过true,否则false</returns>
        public bool CheckRepCount(string reportId)
        {
            string strSql = @"select count(1) from dbo.T_VegBasicInfo where ReportId=@ReportId";
            try
            {
                using (var dbCon = ConnectFactory.GetOpenConnection())
                {
                    //为0，没生成过true,否则false
                    return dbCon.Query<int>(strSql, new { ReportId = reportId }).FirstOrDefault() == 0 ? true : false;
                }
            }
            catch (Exception ex)
            {
                LogHelper.ErrorLog("更新表1蔬菜基本情况表T_VegBasicInfo对象信息失败", ex);
                return false;
            }
        }
        /// <summary>
        /// 根据报表ID获取对应报表数据
        /// </summary>
        /// <param name="areaCode"></param>
        /// <param name="reportCode"></param>
        /// <param name="fillInYear"></param>
        /// <returns></returns>
        public override ResResult<VegBasicInfoEntity> GetModel(string ReportId)
        {
            ResResult<VegBasicInfoEntity> obj = new ResResult<VegBasicInfoEntity>();
            VegBasicInfoEntity model = new VegBasicInfoEntity();
            if (CheckRepCount(ReportId))
            {
                model.ReportId = ReportId;
                if (AddInfo(model).status > 0)
                {
                    obj.model = model;
                    obj.status = DefaultKey.SuccessResult;
                    obj.message = "获取成功！";
                }
            }
            else
            {
                string strSql = @"select * from dbo.T_VegBasicInfo where ReportId = @ReportId";
                try
                {
                    using (var dbCon = ConnectFactory.GetOpenConnection())
                    {
                        obj.model = dbCon.Query<VegBasicInfoEntity>(strSql, new { ReportId = ReportId }).FirstOrDefault();
                        obj.status = DefaultKey.SuccessResult;
                        obj.message = "获取成功！";
                        dbCon.Dispose();//数据库连接释放
                    }
                }
                catch (Exception ex)
                {
                    obj.status = DefaultKey.ErrorResult;
                    obj.message = ex.ToString().Trim();
                    LogHelper.ErrorLog("获取表1蔬菜基本情况调查T_VegBasicInfo对象信息失败", ex);
                }
            }
            return obj;
        }

        /// <summary>
        /// 获取今往年数据
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ResResult<VegBasicInfoViewModel> GetModel(VegNowModel model)
        {
            ResResult<VegBasicInfoViewModel> obj = new ResResult<VegBasicInfoViewModel>();
            VegBasicInfoEntity Entity = new VegBasicInfoEntity();
            VegBasicInfoViewModel viewModel = new VegBasicInfoViewModel();
            var paramlist = new DynamicParameters();
            string strSqlReport = "";
            if (model != null)
            {
                if (!string.IsNullOrEmpty(model.AreaCode) && !string.IsNullOrEmpty(model.ReportCode) && !string.IsNullOrEmpty(model.FillInYear))
                {
                    paramlist.Add("AreaCode", model.AreaCode);
                    paramlist.Add("ReportCode", model.ReportCode);
                    paramlist.Add("FillInYear", model.FillInYear);
                    int OldFillInYear = Convert.ToInt32(model.FillInYear) - 1;
                    if (OldFillInYear < 0)
                    {
                        OldFillInYear = 0;
                    }
                    paramlist.Add("OldFillInYear", OldFillInYear.ToString());
                    string strNowSql = "SELECT vf.Id,vf.ReportId,VegArea,PerennialArea,SeasonArea,WSArea,SFArea,LiquidArea,FacilityArea,Remark,ReportCode,Status as ReportStatus "
                                    + " FROM T_Report r LEFT JOIN T_VegBasicInfo vf on vf.ReportId = r.Id WHERE ReportCode = @ReportCode and FillInYear = @FillInYear and AreaCode = @AreaCode ";
                    string strOldSql = "SELECT vf.Id as OldId,vf.ReportId as OldReportId,VegArea as OldVegArea,PerennialArea as OldPerennialArea,SeasonArea as OldSeasonArea,"
                                    + "WSArea as OldWSArea,SFArea as OldSFArea,LiquidArea as OldLiquidArea,FacilityArea as OldFacilityArea,Remark OldRemark,ReportCode,Status as OldReportStatus "
                                    + " FROM T_Report r LEFT JOIN T_VegBasicInfo vf on vf.ReportId = r.Id WHERE ReportCode = @ReportCode and FillInYear = @OldFillInYear and AreaCode = @AreaCode ";
                    strSqlReport = "SELECT * FROM ((" + strNowSql + ")t LEFT JOIN  (" + strOldSql + ")tt ON t.ReportCode = tt.ReportCode)";

                    //判断选择的年度与上一年度是否生成过报表
                    if (CheckRepCreate(model.ReportCode, model.AreaCode, model.FillInYear) && CheckRepCreate(model.ReportCode, model.AreaCode, OldFillInYear.ToString()))
                    {
                        obj.model = viewModel;
                        obj.status = -1;
                        DictServices dictServices = new DictServices();
                        obj.message = dictServices.GetModel("ReportYear", model.FillInYear).model.DictText + "的报表无需填报！！";
                        return obj;
                    }
                    //判断本年是否生成过报表
                    else if (CheckRepCreate(model.ReportCode, model.AreaCode, model.FillInYear))
                    {
                        var dbCon = ConnectFactory.GetOpenConnection();
                        obj.model = dbCon.Query<VegBasicInfoViewModel>(strSqlReport, paramlist).FirstOrDefault();
                        obj.status = -2;
                        DictServices dictServices = new DictServices();
                        obj.message = dictServices.GetModel("ReportYear", model.FillInYear).model.DictText + "的报表无需填报！！";
                        dbCon.Dispose();//数据库连接释放
                        return obj;
                    }
                    else
                    {
                        //获取报表Id
                        Entity.ReportId = GetReportId(model.ReportCode, model.AreaCode, model.FillInYear);
                        //判断表T_VegFacility是否初始化过
                        if (CheckRepCount(Entity.ReportId))
                        {
                            if (AddInfo(Entity).status > 0)//报表初始化
                            {
                                using (var dbCon = ConnectFactory.GetOpenConnection())
                                {
                                    //查询去年数据
                                    obj.model = dbCon.Query<VegBasicInfoViewModel>(strSqlReport, paramlist).FirstOrDefault();
                                    obj.status = DefaultKey.SuccessResult;//初始化成功status为1
                                    obj.message = "VegBasicInfo报表初始化成功！";
                                    dbCon.Dispose();//数据库连接释放
                                }
                            }
                        }
                        else
                        {
                            try
                            {
                                using (var dbCon = ConnectFactory.GetOpenConnection())
                                {
                                    obj.model = dbCon.Query<VegBasicInfoViewModel>(strSqlReport, paramlist).FirstOrDefault();
                                    obj.status = DefaultKey.SuccessResult;//成功状态为2
                                    obj.message = "获取VegBasicInfo报表今往年数据成功！";
                                    dbCon.Dispose();//数据库连接释放
                                }
                            }
                            catch (Exception ex)
                            {
                                obj.status = 0; //失败状态
                                obj.message = ex.ToString().Trim();
                                LogHelper.ErrorLog("获取VegBasicInfo报表今往年数据失败", ex);
                            }
                        }
                    }
                }
                else
                {
                    obj.message = "当前地区没有对应报表";
                    obj.status = 0;
                }
            }
            else
            {
                obj.message = "参数错误,请与管理员联系!!!";
                obj.status = 0;
            }
            return obj;
        }


        /// <summary>
        /// 根据地区、报表代码、填报年度判断是否生成过报表
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool CheckRepCreate(string ReportCode, string AreaCode, string FillInYear)
        {
            string strSql = @"select count(1) from dbo.T_Report where ReportCode = @ReportCode and AreaCode = @AreaCode and FillInYear = @FillInYear ";
            try
            {
                using (var dbCon = ConnectFactory.GetOpenConnection())
                {
                    //为0，没生成过true,否则false
                    return dbCon.Query<int>(strSql, new { ReportCode = ReportCode, AreaCode = AreaCode, FillInYear = FillInYear }).FirstOrDefault() == 0 ? true : false;
                }
            }
            catch (Exception ex)
            {
                LogHelper.ErrorLog("当前填报年度的表T_VegBasicInfo没有生成过", ex);
                return false;
            }
        }


        /// <summary>
        /// 根据地区、报表代码、填报年度获取报表Id
        /// </summary>
        /// <param name="ReportCode"></param>
        /// <param name="AreaCode"></param>
        /// <param name="FillInYear"></param>
        /// <returns></returns>
        public string GetReportId(string ReportCode, string AreaCode, string FillInYear)
        {
            string strSql = @"select * from dbo.T_Report where ReportCode = @ReportCode and AreaCode = @AreaCode and FillInYear = @FillInYear ";
            try
            {
                using (var dbCon = ConnectFactory.GetOpenConnection())
                {
                    return dbCon.Query<ReportEntity>(strSql, new { ReportCode = ReportCode, AreaCode = AreaCode, FillInYear = FillInYear }).FirstOrDefault().Id;
                }
            }
            catch (Exception ex)
            {
                LogHelper.ErrorLog("当前填报年度的表T_VegBasicInfo没有生成过", ex);
                return "0";
            }
        }


        /// <summary>
        /// 读取导入的Excel数据
        /// </summary>
        /// <param name="pathName">导入文件路径</param>
        /// <param name="fileSuffix">文件后缀</param>
        /// <param name="sheetName">sheet名称</param>
        /// <param name="startRow">从第几行开始读取数据</param>
        /// <returns></returns>
        public List<VegBasicInfoModel> ExcelToModel(string pathName, string fileSuffix, string sheetName, int startRow)
        {

            IWorkbook workbook = null;
            ISheet sheet = null;
            List<VegBasicInfoModel> list = new List<VegBasicInfoModel>();
            FileStream fs = new FileStream(pathName, FileMode.Open, FileAccess.Read);
            switch (fileSuffix)
            {
                case ".xls":
                    workbook = new HSSFWorkbook(fs);
                    break;
                case ".xlsx":
                    workbook = new XSSFWorkbook(fs);
                    break;
                default:
                    workbook = new HSSFWorkbook(fs);
                    break;
            }
            if (!string.IsNullOrEmpty(sheetName))
            {
                sheet = workbook.GetSheet(sheetName);
                if (sheet == null) //如果没有找到指定的sheetName对应的sheet，则尝试获取第一个sheet
                {
                    sheet = workbook.GetSheetAt(0);
                }
            }
            else
            {
                sheet = workbook.GetSheetAt(0);
            }
            if (sheet != null)
            {
                IRow firstRow = sheet.GetRow(3);//从第四行开始读
                int cellCount = firstRow.LastCellNum;//获取列数

                //获取有数据的行数
                int rowCount = 0;
                for (int i = startRow; i <= sheet.LastRowNum; i++)
                {
                    IRow row = sheet.GetRow(i);
                    if (row != null)
                    {
                        rowCount = sheet.GetRow(i).RowNum;
                    }
                    else
                    {
                        break;
                    }
                }
                for (int i = startRow; i <= rowCount; i++)
                {
                    IRow row = sheet.GetRow(i);
                    VegBasicInfoModel model = new VegBasicInfoModel();
                    //model.year = row.GetCell(0).ToString();
                    //蔬菜占地面积
                    model.VegArea = decimal.Zero;
                    //常年蔬菜占地面积
                    if (row.GetCell(1) != null && row.GetCell(1).ToString() != "")
                    {
                        model.PerennialArea = decimal.Parse(row.GetCell(1).ToString());
                        model.VegArea += model.PerennialArea;
                    }
                    else
                    {
                        model.PerennialArea = null;
                    }
                    //冬春季蔬菜占地面积
                    if (row.GetCell(4) != null && row.GetCell(4).ToString() != "")
                    {
                        model.WSArea = decimal.Parse(row.GetCell(4).ToString());
                        model.VegArea += model.WSArea;
                    }
                    else
                    {
                        model.WSArea = null;
                    }
                    //夏秋季蔬菜占地面积
                    if (row.GetCell(7) != null && row.GetCell(7).ToString() != "")
                    {
                        model.SFArea = decimal.Parse(row.GetCell(7).ToString());
                        model.VegArea += model.SFArea;
                    }
                    else
                    {
                        model.SFArea = null;
                    }
                    //菜地喷滴灌蔬菜占地面积
                    if (row.GetCell(10) != null && row.GetCell(10).ToString() != "")
                    {
                        model.FacilityArea = decimal.Parse(row.GetCell(10).ToString());
                    }
                    else
                    {
                        model.FacilityArea = null;
                    }
                    //水生蔬菜占地面积
                    if (row.GetCell(13) != null && row.GetCell(13).ToString() != "")
                    {
                        model.LiquidArea = decimal.Parse(row.GetCell(13).ToString());
                    }
                    else
                    {
                        model.LiquidArea = null;
                    }
                    if (row.GetCell(16) != null && row.GetCell(16).ToString() != "")
                    {
                        model.Remark = row.GetCell(16).ToString().Trim();
                    }
                    else
                    {
                        model.Remark = null;
                    }
                    list.Add(model);
                }
            }
            return list;
        }

        /// <summary>
        /// 添加
        /// </summary>
        public virtual ResResult<int> AddInfo(VegBasicInfoModel model)
        {
            ResResult<int> obj = new ResResult<int>();
            string strSql = @"INSERT INTO dbo.T_VegBasicInfo";
            strSql += "(";
            strSql += "Id,";
            strSql += "ReportId,";
            strSql += "VegArea,";
            strSql += "PerennialArea,";
            strSql += "SeasonArea,";
            strSql += "WSArea,";
            strSql += "SFArea,";
            strSql += "LiquidArea,";
            strSql += "Remark,";
            strSql += "FacilityArea)";
            strSql += " values(";
            strSql += "@Id,";
            strSql += "@ReportId,";
            strSql += "@VegArea,";
            strSql += "@PerennialArea,";
            strSql += "@SeasonArea,";
            strSql += "@Remark,";
            strSql += "@WSArea,";
            strSql += "@SFArea,";
            strSql += "@LiquidArea,";
            strSql += "@FacilityArea)";
            try
            {
                using (var dbCon = ConnectFactory.GetOpenConnection())
                {
                    model.Id = CustomFun.GetGuid();
                    int result = dbCon.Execute(strSql, model);
                    if (result > 0)
                    {
                        obj.model = result;
                        obj.status = DefaultKey.SuccessResult;
                        obj.message = "添加成功！";
                    }
                    else
                    {
                        obj.model = result;
                        obj.status = DefaultKey.InfoResult;
                        obj.message = "添加失败！数量为:" + result;
                    }
                    dbCon.Dispose();//数据库连接释放
                    return obj;
                }
            }
            catch (Exception ex)
            {
                obj.status = DefaultKey.ErrorResult;
                obj.message = ex.ToString().Trim();
                LogHelper.ErrorLog("新增表1蔬菜基本情况调查T_VegBasicInfo对象信息失败", ex);
                return obj;
            }
        }
        /// <summary>
        /// 导出数据
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public MemoryStream Method(VegNowModel model)
        {
            model.FillInYear = dict.GetKey("ReportYear", model.FillInYear);
            FileStream file = null;
            //创建下载Excel文件
            var workbook = new HSSFWorkbook();
            string fileIndex = HttpRuntime.AppDomainAppPath.ToString();
            string filename = @"tempfile\Basic" + DateTime.Now.Ticks.ToString() + ".xls";//临时文件，定期在tempfile手动删除
            string tempExcel = fileIndex + filename;//临时文件路径及全称
            string templateName = fileIndex + @"Excel\VegDownload.xls";//模板文件
            file = new FileStream(templateName, FileMode.Open, FileAccess.Read);//读模板文件
            HSSFWorkbook templateBook = new HSSFWorkbook(file);//读取模板文件信息转换成Excel工作薄
            HSSFSheet sheet = templateBook.GetSheet("VegBasicInfo") as HSSFSheet;//读取模板所在sheet位置
            VegBasicInfoViewModel pageModel = GetModel(model).model;//数据获取

            HSSFRow row = (HSSFRow)sheet.GetRow(1);//读取模板第二行
            var style = row.GetCell(0).CellStyle;//读取模板第二行第一单元格样式并保存
            row.GetCell(0).CellStyle = style;//对第二行第一单元格设置原来样式

            HSSFRow datarow = (HSSFRow)sheet.CreateRow(3);
            datarow.CreateCell(0).SetCellValue(pageModel.VegArea == null ? "" : Common.GetADecimal(pageModel.VegArea));//蔬菜占地面积
            datarow.CreateCell(1).SetCellValue(pageModel.PerennialArea == null ? "" : Common.GetADecimal(pageModel.PerennialArea));//常年蔬菜占地面积
            datarow.CreateCell(2).SetCellValue(pageModel.OldPerennialArea == null ? "" : Common.GetADecimal(pageModel.OldPerennialArea));
            datarow.CreateCell(3).SetCellValue(Common.GetDivision(pageModel.OldPerennialArea, pageModel.PerennialArea));//增减比
            datarow.CreateCell(4).SetCellValue(pageModel.WSArea == null ? "" : Common.GetADecimal(pageModel.WSArea));//冬春季蔬菜面积
            datarow.CreateCell(5).SetCellValue(pageModel.OldWSArea == null ? "" : Common.GetADecimal(pageModel.OldWSArea));
            datarow.CreateCell(6).SetCellValue(Common.GetDivision(pageModel.OldWSArea, pageModel.WSArea));//
            datarow.CreateCell(7).SetCellValue(pageModel.SFArea == null ? "" : Common.GetADecimal(pageModel.SFArea));//春夏季蔬菜面积
            datarow.CreateCell(8).SetCellValue(pageModel.OldSFArea == null ? "" : Common.GetADecimal(pageModel.OldSFArea));//
            datarow.CreateCell(9).SetCellValue(Common.GetDivision(pageModel.OldSFArea, pageModel.SFArea));//增减比%
            datarow.CreateCell(10).SetCellValue(pageModel.FacilityArea == null ? "" : Common.GetADecimal(pageModel.FacilityArea));//菜地喷滴灌面积
            datarow.CreateCell(11).SetCellValue(pageModel.OldFacilityArea == null ? "" : Common.GetADecimal(pageModel.OldFacilityArea));//
            datarow.CreateCell(12).SetCellValue(Common.GetDivision(pageModel.OldFacilityArea, pageModel.FacilityArea));//增减比
            datarow.CreateCell(13).SetCellValue(pageModel.LiquidArea == null ? "" : Common.GetADecimal(pageModel.LiquidArea));//水生蔬菜面积
            datarow.CreateCell(14).SetCellValue(pageModel.OldLiquidArea == null ? "" : Common.GetADecimal(pageModel.OldLiquidArea));//
            datarow.CreateCell(15).SetCellValue(Common.GetDivision(pageModel.OldLiquidArea, pageModel.LiquidArea));//
            datarow.CreateCell(16).SetCellValue(pageModel.Remark == null ? "" : pageModel.Remark.ToString());//备注
            //for (int i=0;i<17;i++)
            //{
            //    datarow.CreateCell(i).CellStyle = style;
            //}

            sheet.CopyTo(workbook, "Sheet1", true, true);
            using (MemoryStream ms = new MemoryStream())
            {
                workbook.Write(ms);
                ms.Flush();
                ms.Position = 0;
                return ms;
            }
        }
        /// <summary>
        /// 修改\更新
        /// </summary>
        public virtual ResResult<int> UpdateInfo(VegBasicInfoModel model)
        {
            ResResult<int> obj = new ResResult<int>();
            ReportServices reportServices = new ReportServices();
            if (model != null)
            {
                string strSql = @"UPDATE dbo.T_VegBasicInfo set ";
                strSql += "VegArea = @VegArea,";
                strSql += "PerennialArea = @PerennialArea,";
                strSql += "SeasonArea = @SeasonArea,";
                strSql += "WSArea = @WSArea,";
                strSql += "SFArea = @SFArea,";
                strSql += "LiquidArea = @LiquidArea,";
                strSql += "Remark = @Remark,";
                strSql += "FacilityArea = @FacilityArea ";
                strSql += " where ReportId = @ReportId";
                try
                {
                    using (var dbCon = ConnectFactory.GetOpenConnection())
                    {
                        int result = dbCon.Execute(strSql, model);
                        if (result > 0)
                        {
                            obj.model = result;
                            obj.status = DefaultKey.SuccessResult;
                            obj.message = "数据更新成功！";
                        }
                        else
                        {
                            obj.model = result;
                            obj.status = DefaultKey.InfoResult;
                            obj.message = "更新失败！数量为:" + result;
                        }
                        dbCon.Dispose();//数据库连接释放
                    }
                }
                catch (Exception ex)
                {
                    obj.status = DefaultKey.ErrorResult;
                    obj.message = ex.ToString().Trim();
                    LogHelper.ErrorLog("更新表1蔬菜基本情况调查T_VegBasicInfo对象信息失败", ex);
                }
            }
            return obj;
        }
        public ResResult<List<VegBasicInfoStatsModel>> GetStatsList(VegNowModel model)
        {
            DictServices dictServices = new DictServices();
            ResResult<List<VegBasicInfoStatsModel>> result = new ResResult<List<VegBasicInfoStatsModel>>();
            var paramlist = new DynamicParameters();
            int OldFillInYear = 0;
            if (!string.IsNullOrEmpty(model.AreaCode))
            {
                paramlist.Add("AreaCode", model.AreaCode);
            }
            if (!string.IsNullOrEmpty(model.FillInYear))
            {
                model.FillInYear = dictServices.GetKey("ReportYear", model.FillInYear); ;
                OldFillInYear = Convert.ToInt32(model.FillInYear) - 1;//上一年
                if (OldFillInYear < 0)
                {
                    OldFillInYear = 0;
                }
                paramlist.Add("FillInYear", model.FillInYear);
                paramlist.Add("OldFillInYear", OldFillInYear);
            }
            if (!string.IsNullOrEmpty(model.Status))
            {
                paramlist.Add("Status", model.Status);
            }
            #region 当年统计数据
            string strNowSql = "select Area.Code AreaCode,Dict.DictText FillYear, FullName AreaName,Coord";
            strNowSql += ", ISNULL(VegArea,0.00) VegArea    ";
            strNowSql += ",ISNULL(FacilityArea, 0.00) FacilityArea    ";
            strNowSql += ",ISNULL(LiquidArea, 0.00) LiquidArea    ";
            strNowSql += ",ISNULL(PerennialArea, 0.00) PerennialArea    ";
            strNowSql += ",ISNULL(WSArea, 0.00) WSArea    ";
            strNowSql += ",ISNULL(SFArea, 0.00) SFArea    ";
            strNowSql += "from(    ";
            strNowSql += "select     ";
            if (model.AreaCode == DefaultKey.ProvinceCode || string.IsNullOrEmpty(model.AreaCode))
            {
                strNowSql += "case when grouping(Area.ParentCode) = 1 then @AreaCode else ParentCode end ParentCode,    ";
            }
            else
            {
                strNowSql += "case when grouping(Area.Code) = 1 then @AreaCode else Code end Code,    ";
            }
            strNowSql += "SUM(ISNULL(VegBasicInfo.VegArea, 0.00))  VegArea,    "; //--菜地占地面积
            strNowSql += "SUM(ISNULL(VegBasicInfo.FacilityArea, 0.00))  FacilityArea,     "; //--菜地喷滴灌蔬菜占地面积
            strNowSql += "SUM(ISNULL(VegBasicInfo.LiquidArea, 0.00)) LiquidArea,     "; //--水生蔬菜占地面积
            strNowSql += "SUM(ISNULL(VegBasicInfo.PerennialArea, 0.00)) PerennialArea,     "; //--常年蔬菜占地面积
            strNowSql += "SUM(ISNULL(VegBasicInfo.WSArea, 0.00)) WSArea,     "; //--冬春季蔬菜占地面积
            strNowSql += "SUM(ISNULL(VegBasicInfo.SFArea, 0.00))  SFArea    "; //--夏秋季蔬菜占地面积
            strNowSql += "from[dbo].[T_Report] Report    ";
            strNowSql += "left join[dbo].[T_VegBasicInfo] VegBasicInfo on Report.Id = VegBasicInfo.ReportId    ";
            strNowSql += "right join T_Area Area on Area.Code = Report.AreaCode    ";
            strNowSql += "where    ";
            if (model.AreaCode == DefaultKey.ProvinceCode || string.IsNullOrEmpty(model.AreaCode))
            {
                strNowSql += "Area.ParentCode! = @AreaCode    ";
            }
            else
            {
                strNowSql += "Area.ParentCode = @AreaCode    ";
            }
            strNowSql += "and Report.FillInYear = @FillInYear    ";
            strNowSql += "and Report.Status = @Status     "; //--表示审核通过
            if (model.AreaCode == DefaultKey.ProvinceCode || string.IsNullOrEmpty(model.AreaCode))
            {
                strNowSql += "group by rollup(Area.ParentCode)    ";
            }
            else
            {
                strNowSql += "group by rollup(Area.Code)    ";
            }
            strNowSql += ") tt1    ";
            if (model.AreaCode == DefaultKey.ProvinceCode || string.IsNullOrEmpty(model.AreaCode))
            {
                strNowSql += "right join T_Area  Area on Area.Code=tt1.ParentCode       ";
            }
            else
            {
                strNowSql += "right join T_Area Area  on tt1.Code=Area.Code   ";
            }
            strNowSql += "inner join T_Dict Dict  on Dict.GroupCode = 'ReportYear' and DictValue = @FillInYear    ";
            strNowSql += "where Area.ParentCode = @AreaCode  or Area.Code = @AreaCode    ";
            #endregion
            #region 上一年统计数据
            string strOldSql = "select Area.Code AreaCode,Dict.DictText FillYear, FullName AreaName,Coord";
            strOldSql += ", ISNULL(VegArea,0.00) OldVegArea    ";
            strOldSql += ",ISNULL(FacilityArea, 0.00) OldFacilityArea    ";
            strOldSql += ",ISNULL(LiquidArea, 0.00) OldLiquidArea    ";
            strOldSql += ",ISNULL(PerennialArea, 0.00) OldPerennialArea    ";
            strOldSql += ",ISNULL(WSArea, 0.00) OldWSArea    ";
            strOldSql += ",ISNULL(SFArea, 0.00) OldSFArea    ";
            strOldSql += "from(    ";
            strOldSql += "select     ";
            if (model.AreaCode == DefaultKey.ProvinceCode || string.IsNullOrEmpty(model.AreaCode))
            {
                strOldSql += "case when grouping(Area.ParentCode) = 1 then @AreaCode else ParentCode end ParentCode,    ";
            }
            else
            {
                strOldSql += "case when grouping(Area.Code) = 1 then @AreaCode else Code end Code,    ";
            }
            strOldSql += "SUM(ISNULL(VegBasicInfo.VegArea, 0.00))  VegArea,    "; //--菜地占地面积
            strOldSql += "SUM(ISNULL(VegBasicInfo.FacilityArea, 0.00))  FacilityArea,     "; //--菜地喷滴灌蔬菜占地面积
            strOldSql += "SUM(ISNULL(VegBasicInfo.LiquidArea, 0.00)) LiquidArea,     "; //--水生蔬菜占地面积
            strOldSql += "SUM(ISNULL(VegBasicInfo.PerennialArea, 0.00)) PerennialArea,     "; //--常年蔬菜占地面积
            strOldSql += "SUM(ISNULL(VegBasicInfo.WSArea, 0.00)) WSArea,     "; //--冬春季蔬菜占地面积
            strOldSql += "SUM(ISNULL(VegBasicInfo.SFArea, 0.00))  SFArea    "; //--夏秋季蔬菜占地面积
            strOldSql += "from[dbo].[T_Report] Report    ";
            strOldSql += "left join[dbo].[T_VegBasicInfo] VegBasicInfo on Report.Id = VegBasicInfo.ReportId    ";
            strOldSql += "right join T_Area Area on Area.Code = Report.AreaCode    ";
            strOldSql += "where    ";
            if (model.AreaCode == DefaultKey.ProvinceCode || string.IsNullOrEmpty(model.AreaCode))
            {
                strOldSql += "Area.ParentCode! = @AreaCode    ";
            }
            else
            {
                strOldSql += "Area.ParentCode = @AreaCode    ";
            }
            strOldSql += "and Report.FillInYear = @OldFillInYear    ";
            strOldSql += "and Report.Status = @Status     "; //--表示审核通过
            if (model.AreaCode == DefaultKey.ProvinceCode || string.IsNullOrEmpty(model.AreaCode))
            {
                strOldSql += "group by rollup(Area.ParentCode)    ";
            }
            else
            {
                strOldSql += "group by rollup(Area.Code)    ";
            }
            strOldSql += ") tt1    ";
            if (model.AreaCode == DefaultKey.ProvinceCode || string.IsNullOrEmpty(model.AreaCode))
            {
                strOldSql += "right join T_Area  Area on Area.Code=tt1.ParentCode       ";
            }
            else
            {
                strOldSql += "right join T_Area Area on Area.Code = tt1.Code    ";
            }
            strOldSql += "inner join T_Dict Dict  on Dict.GroupCode = 'ReportYear' and DictValue = @FillInYear    ";
            strOldSql += "where Area.ParentCode = @AreaCode  or Area.Code = @AreaCode    ";
            #endregion
            string strCitySql = "SELECT * FROM ((" + strNowSql + ")t LEFT JOIN  (" + strOldSql + ")tt ON t.AreaCode = tt.AreaCode) order by t.AreaCode";
            try
            {
                using (var dbCon = ConnectFactory.GetOpenConnection())
                {
                    //查询去年数据
                    result.model = dbCon.Query<VegBasicInfoStatsModel>(strCitySql, paramlist).ToList();
                    result.status = DefaultKey.SuccessResult;//初始化成功status为1
                    result.message = "VegBasicInfo报表统计数据获取成功！";
                    dbCon.Dispose();//数据库连接释放
                }
            }
            catch (Exception ex)
            {
                result.status = DefaultKey.ErrorResult;
                result.message = "VegBasicInfo报表统计数据获取失败" + ex.ToString().Trim();
            }
            return result;
        }
        ///获取统计数据详情
        public ResResult<List<VegBasicInfoStatsModel>> GetDetailStats(VegNowModel model)
        {
            ResResult<List<VegBasicInfoStatsModel>> res = new ResResult<List<VegBasicInfoStatsModel>>();
            List<VegBasicInfoStatsModel> list = new List<VegBasicInfoStatsModel>();
            string ProvinceCode = DefaultKey.ProvinceCode;
            string FillInYear = model.FillInYear;
            try
            {
                if (model.AreaCode == ProvinceCode)
                {
                    var First = GetStatsList(model).model;
                    First[0].AreaName = "合计";
                    list.Add(First[0]);//省级汇总合计
                    foreach (var item in First)
                    {
                        if (item.AreaCode != ProvinceCode)
                        {
                            VegNowModel model2 = new VegNowModel();
                            model2.FillInYear = FillInYear;
                            model2.AreaCode = item.AreaCode;
                            model2.Status = model.Status;
                            var Second = GetStatsList(model2).model;
                            list.Add(item);
                            foreach (var item2 in Second)
                            {
                                if (model2.AreaCode != item2.AreaCode)
                                {
                                    list.Add(item2);
                                }
                            }
                        }
                    }
                }
                else
                {
                    list = GetStatsList(model).model;//数据获取
                }
            }
            catch (Exception ex)
            {
                res.model = list;
                res.message = "获取统计数据详情失败" + ex.ToString().Trim();
                res.status = DefaultKey.SuccessResult;
            }
            if (list != null)
            {
                res.model = list;
                res.message = "获取统计数据详情成功";
                res.status = DefaultKey.SuccessResult;
            }
            else
            {
                res.message = "获取统计数据详情成失败";
                res.status = DefaultKey.ErrorResult;
            }
            return res;
        }
        /// <summary>
        /// 统计数据导出
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public MemoryStream MethodStats(VegNowModel model)
        {
            string FillInYear = model.FillInYear;
            AreaServices areaServices = new AreaServices();
            //创建下载Excel文件
            var workbook = new HSSFWorkbook();
            string AreaName = areaServices.GetByCodeModel(model.AreaCode).model.Name;
            if (model.AreaCode == DefaultKey.ProvinceCode)//判断当前用户是否为省级用户
            {
                //州市汇总情况

                getExcelStatsList(workbook, GetStatsList(model).model, AreaName + "_州市");//省级汇总(针对州市)
                //区县详情
                model.FillInYear = FillInYear;
                AreaName = areaServices.GetByCodeModel(model.AreaCode).model.Name == "云南省" ? "云南省_县(市、州)" : areaServices.GetByCodeModel(model.AreaCode).model.Name;//获取当前行政区划名称
                getExcelStatsList(workbook, GetDetailStats(model).model, AreaName);//省级汇总(针对区县)
                var areaList = areaServices.GetPrefectureList();//获取州市级列表
                foreach (var areaCode in areaList)
                {
                    model.AreaCode = areaCode;
                    model.FillInYear = FillInYear;
                    getExcelStatsList(workbook, GetDetailStats(model).model, areaServices.GetByCodeModel(areaCode).model.Name);
                }
            }
            else
            {
                getExcelStatsList(workbook, GetDetailStats(model).model, AreaName);//省级汇总(针对区县)
            }
            using (MemoryStream ms = new MemoryStream())
            {
                workbook.Write(ms);
                ms.Flush();
                ms.Position = 0;
                return ms;
            }
        }
        /// <summary>
        /// 返回excel工作簿
        /// </summary>
        /// <param name="workbook">工作簿</param>
        /// <param name="sheet">子表</param>
        /// <param name="model"></param>
        /// <param name="AreaName">地区名称</param>
        /// <returns></returns>
        public HSSFWorkbook getExcelStatsList(HSSFWorkbook workbook, List<VegBasicInfoStatsModel> list, string AreaName)
        {
            FileStream file = null;
            string fileIndex = HttpRuntime.AppDomainAppPath.ToString();
            string filename = @"tempfile\Basic" + DateTime.Now.Ticks.ToString() + ".xls";//临时文件，定期在tempfile手动删除
            string tempExcel = fileIndex + filename;//临时文件路径及全称
            string templateName = fileIndex + @"Excel\VegStatsDownload.xls";//模板文件
            file = new FileStream(templateName, FileMode.Open, FileAccess.Read);//读模板文件
            HSSFWorkbook templateBook = new HSSFWorkbook(file);//读取模板文件信息转换成Excel工作薄
            HSSFSheet sheet = templateBook.GetSheet("VegBasicInfo") as HSSFSheet;//读取模板所在sheet位置
            HSSFRow row = (HSSFRow)sheet.GetRow(1);//读取模板第二行
            var style = row.GetCell(0).CellStyle;//读取模板第二行第一单元格样式并保存
            row.GetCell(0).CellStyle = style;//对第二行第一单元格设置原来样式
            if (list != null)
            {
                for (int i = 0; i < list.Count; i++)
                {
                    HSSFRow datarow = (HSSFRow)sheet.CreateRow(i + 3);
                    style.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.Black.Index;
                    if (i == 0)
                    {
                        list[0].AreaName = "合计";
                        datarow.RowStyle = style;
                    }
                    datarow.CreateCell(0).SetCellValue(list[i].AreaName == null ? "" : list[i].AreaName.ToString());//地区
                    datarow.CreateCell(1).SetCellValue(list[i].VegArea == null ? "" : Common.GetADecimal(list[i].VegArea));//蔬菜占地面积
                    datarow.CreateCell(2).SetCellValue(list[i].PerennialArea == null ? "" : Common.GetADecimal(list[i].PerennialArea));//常年蔬菜占地面积
                    datarow.CreateCell(3).SetCellValue(list[i].OldPerennialArea == null ? "" : Common.GetADecimal(list[i].OldPerennialArea));
                    datarow.CreateCell(4).SetCellValue(Common.GetDivision(list[i].OldPerennialArea, list[i].PerennialArea));//增减比%
                    datarow.CreateCell(5).SetCellValue(list[i].WSArea == null ? "" : Common.GetADecimal(list[i].WSArea));//冬春季蔬菜面积
                    datarow.CreateCell(6).SetCellValue(list[i].OldWSArea == null ? "" : Common.GetADecimal(list[i].OldWSArea));
                    datarow.CreateCell(7).SetCellValue(Common.GetDivision(list[i].OldWSArea, list[i].WSArea));//增减比%
                    datarow.CreateCell(8).SetCellValue(list[i].SFArea == null ? "" : Common.GetADecimal(list[i].SFArea));//春夏季蔬菜面积
                    datarow.CreateCell(9).SetCellValue(list[i].OldSFArea == null ? "" : Common.GetADecimal(list[i].OldSFArea));//
                    datarow.CreateCell(10).SetCellValue(Common.GetDivision(list[i].OldSFArea, list[i].SFArea));//增减比%
                    datarow.CreateCell(11).SetCellValue(list[i].FacilityArea == null ? "" : Common.GetADecimal(list[i].FacilityArea));//菜地喷滴灌面积
                    datarow.CreateCell(12).SetCellValue(list[i].OldFacilityArea == null ? "" : Common.GetADecimal(list[i].OldFacilityArea));//
                    datarow.CreateCell(13).SetCellValue(Common.GetDivision(list[i].OldFacilityArea, list[i].FacilityArea));//增减比
                    datarow.CreateCell(14).SetCellValue(list[i].LiquidArea == null ? "" : Common.GetADecimal(list[i].LiquidArea));//水生蔬菜面积
                    datarow.CreateCell(15).SetCellValue(list[i].OldLiquidArea == null ? "" : Common.GetADecimal(list[i].OldLiquidArea));//
                    datarow.CreateCell(16).SetCellValue(Common.GetDivision(list[i].OldLiquidArea, list[i].LiquidArea));//增减比
                    for (int j = 0; j < 17; j++)
                    {
                        datarow.GetCell(j).CellStyle = style;
                    }
                }
                sheet.CopyTo(workbook, AreaName, true, true);
            }
            return workbook;
        }
    }
}